//
//  LoadGltfDemoVC.m
//  FilamentDemo
//
//  Created by jerry on 2020/5/4.
//  Copyright © 2020 tencent. All rights reserved.
//

#import "LoadGltfDemoVC.h"
#import "FilamentConvenientHeader.h"

@interface LoadGltfDemoVC ()
@property (nonatomic, assign) gltfio::FilamentAsset *glbAsset;
@property (nonatomic, strong) NSData *glbData;
@property (nonatomic, assign) gltfio::AssetLoader *assetLoader;
@property (nonatomic, assign) float animationProgress;
@end

@implementation LoadGltfDemoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //暂不明何意: Creates a material provider that loads a small set of pre-built materials.
    gltfio::MaterialProvider *materialProvider = gltfio::createUbershaderLoader(self.render.engine);
    
    /*
     AssetLoader将glTF 2.0的内容（JSON或GLB），转换成FilamentAsset
     对象，其中包含了entities, material instances, textures, vertex buffers, index buffers.
     */
    _assetLoader = gltfio::AssetLoader::create({self.render.engine, materialProvider, nullptr});
    
    
    NSString *glbFile = [[NSBundle mainBundle] pathForResource:@"bird.glb" ofType:nil];
    _glbData = [NSData dataWithContentsOfFile:glbFile];
    
    _glbAsset = _assetLoader->createAssetFromBinary((uint8_t *)[_glbData bytes],
                                                    (uint32_t)_glbData.length);
    //从文件中加载资源: 读取顶点数据、解码图片文件、读取切线信息等。
    gltfio::ResourceLoader({
     .engine = self.render.engine,
    }).loadResources(_glbAsset);
    
    auto &tcm = self.render.engine->getTransformManager();

    mat4f t = mat4f::scaling(float3{0.05, 0.05, 0.05});
    
    tcm.setTransform(tcm.getInstance(_glbAsset->getRoot()), t);
    
    self.render.scene->addEntities(_glbAsset->getEntities(),
                                   _glbAsset->getEntityCount());
}

//override
- (void)callbackPerRenderFrame{
    _animationProgress += 0.03;
    if (_animationProgress >= 1) {
        _animationProgress = 0;
    }
    gltfio::Animator *animator = _glbAsset->getAnimator();
    float duration = animator->getAnimationDuration(0);
    animator->applyAnimation(0, duration * _animationProgress);
    animator->updateBoneMatrices(); //更新骨骼动画所有节点的矩阵
}

- (void)dealloc{
    _assetLoader->destroyAsset(_glbAsset);
    gltfio::AssetLoader::destroy(&_assetLoader);
}
@end
